<template>
  <div id="app">
    <!--面包屑导航区域-->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="#">商品管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图区域-->
    <el-card class="box-card">
      <!-- 警告提示文案 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 选择商品分类级联选择器 -->
      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectedKeys"
            :options="cateList"
            :props="cascaderProps"
            @change="handleChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tabs页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            @click="addDialogVisible = true"
            size="mini"
            :disabled="isBtnDisable"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="activeList" border stripe>
            <!-- 开头的展开行 -->
            <el-table-column type="expand" v-slot="scope">
              <!-- 循环渲染tag标签 -->
              <el-tag
                v-for="(item, i) in scope.row.attr_vals"
                :key="i"
                closable
                size="small"
                @close="handleClosed(i, scope.row)"
                >{{ item }}</el-tag
              >
              <el-input
                class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(scope.row)"
                >+ New Tag</el-button
              >
            </el-table-column>
            <!-- 第一行利用type加上index做成了索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作" v-slot="scope">
              <el-button
                type="primary"
                @click="editParams(scope.row.attr_id)"
                size="mini"
                icon="el-icon-edit"
                >修改参数</el-button
              >
              <el-button
                type="danger"
                @click="deleteParams(scope.row.attr_id)"
                size="mini"
                icon="el-icon-delete"
                >删除参数</el-button
              >
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            @click="addDialogVisible = true"
            size="mini"
            :disabled="isBtnDisable"
            >添加属性</el-button
          >
          <!-- 静态属性表格 -->
          <el-table :data="staticList" border stripe>
            <!-- 开头的展开行 -->
            <el-table-column type="expand" v-slot="scope">
              <!-- 循环渲染tag标签 -->
              <el-tag
                v-for="(item, i) in scope.row.attr_vals"
                :key="i"
                closable
                size="small"
                @close="handleClosed(i, scope.row)"
                >{{ item }}</el-tag
              >
              <el-input
                class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(scope.row)"
                >+ New Tag</el-button
              >
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作" v-slot="scope">
              <el-button
                type="primary"
                @click="editParams(scope.row.attr_id)"
                size="mini"
                icon="el-icon-edit"
                >修改参数</el-button
              >
              <el-button
                type="danger"
                @click="deleteParams(scope.row.attr_id)"
                size="mini"
                icon="el-icon-delete"
                >删除参数</el-button
              >
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加：' + title"
      :visible.sync="addDialogVisible"
      width="30%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addParamsForm"
        :rules="addParamsRules"
        ref="addParamsRef"
        label-width="100px"
      >
        <el-form-item :label="title + ':'" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamsButton">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数对话框 -->
    <el-dialog
      :title="'修改：' + title"
      :visible.sync="editDialogVisible"
      width="30%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editParamsForm"
        :rules="editParamsRules"
        ref="editParamsRef"
        label-width="100px"
      >
        <el-form-item :label="title + ':'" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamsButton">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 级联选择器数据来源
      cateList: [],
      // 级联选择器属性配置
      cascaderProps: {
        expandTrigger: 'hover',
        children: 'children',
        label: 'cat_name',
        value: 'cat_id'
      },
      //级联选择器双向绑定的id
      selectedKeys: [],
      //默认选中的页签属性，相当于不同页签不同id,默认动态
      activeName: 'many',
      // 添加按钮的禁用与解除
      isBtnDisable: true,
      // 参数&属性数据列表
      activeList: [],
      staticList: [],
      // 控制添加对话框的显示与隐藏
      addDialogVisible: false,
      // 添加参数表单数据绑定
      addParamsForm: {
        attr_name: ''
      },
      // 添加参数的表单验证规则
      addParamsRules: {
        attr_name: [
          { required: true, message: '请添加名称', trigger: 'blur' },
          { min: 2, max: 6, message: '名称在2到6个字符', trigger: 'blur' }
        ]
      },
      // 控制修改参数对话框的显示与隐藏
      editDialogVisible: false,
      // 编辑参数表单数据绑定
      editParamsForm: {
        attr_name: ''
      },
      // 编辑参数的表单验证规则
      editParamsRules: {
        attr_name: [
          { required: true, message: '请添加名称', trigger: 'blur' },
          { min: 2, max: 6, message: '名称在2到6个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取商品分类数据列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 3 }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败')
      }
      this.cateList = res.data
    },
    //级联选择器选定触发事件
    handleChange() {
      // 控制添加按钮的禁用与解除
      this.isBtnDisable = false
      this.getparams()
    },
    // 页签点击事件
    handleClick() {
      this.getparams()
    },
    //通过id查询参数
    async editParams(row) {
      const { data: res } = await this.$http.get(
        `categories/${this.selectedKeys[2]}/attributes/${row}`,
        {
          params: {
            attr_sel: this.activeName
          }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败')
      }
      this.editParamsForm = res.data
      this.editDialogVisible = true
    },

    // 获取商品参数&属性数据
    async getparams() {
      //用户没有选择级联选择器却点击了页签
      if (this.selectedKeys.length === 0) {
        this.selectedKeys = []
        this.activeList = []
        this.staticList = []
        return
      }
      //获取商品参数&属性数据
      const { data: res } = await this.$http.get(
        `categories/${this.selectedKeys[2]}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      if (res.meta.status !== 200) {
        this.$message.error('获取商品数据失败')
      }
      //获取的数据项attr_vals要用空格隔开
      console.log(res.data)
      res.data.forEach(item => {
        //判断item.attr_vals是否为空，空就返回空数组，不为空就用空格分隔
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 每个参数创建属于自己的inputVisible&inputValue
        item.inputVisible = false
        item.inputValue = ''
      })
      //判断获取的参数数据动态还是静态
      if (this.activeName === 'only') {
        this.staticList = res.data
      } else {
        this.activeList = res.data
      }
    },

    // 验证规则&提交添加参数请求
    addParamsButton() {
      this.$refs.addParamsRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.selectedKeys[2]}/attributes`,
          {
            attr_name: this.addParamsForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加数据失败')
        }
        this.$message.success('更新数据成功')
        this.addDialogVisible = false
        this.getparams()
      })
    },
    //重置添加参数表单
    addDialogClosed() {
      this.$refs.addParamsRef.resetFields()
    },
    editDialogClosed() {
      this.$refs.editParamsRef.resetFields()
    },
    // 编辑表单验证规则&提交添加参数请求
    editParamsButton() {
      this.$refs.editParamsRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.selectedKeys[2]}/attributes/${this.editParamsForm.attr_id}`,
          {
            attr_name: this.editParamsForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('更新数据失败')
        }
        this.$message.success('更新数据成功')
        this.editDialogVisible = false
        this.getparams()
      })
    },
    // 删除参数
    async deleteParams(row) {
      const delresult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(error => error)
      if (delresult !== 'confirm') {
        return this.$message({ type: 'info', message: '已取消删除' })
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.selectedKeys[2]}/attributes/${row}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除参数失败')
      }
      this.$message.success('删除数据成功')
      this.getparams()
    },
    // 文本框按钮点击切换为输入框&获得焦点
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    //提交增加的attr_vals，文本框输入检测不合法的空格
    handleInputConfirm(row) {
      // 检测不合法空格输入，重置文本框状态
      if (row.inputValue.trim(' ') === '') {
        row.inputVisible = false
        row.inputValue = ''
        return
      }
      row.attr_vals.push(row.inputValue.trim(' '))
      row.inputVisible = false
      row.inputValue = ''
      this.saveParams(row)
    },
    // el-tag删除事件
    handleClosed(i, row) {
      row.attr_vals.splice(i, 1)
      this.saveParams(row)
    },
    // 将新增的attr_vals保存到数据库中
    async saveParams(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.selectedKeys[2]}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('添加失败')
      }
      this.$message.success('更新成功')
    }
  },
  // 计算属性
  computed: {
    // 添加参数&属性对话框title
    title() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>
<style lang="less" scoped>
.el-row {
  margin: 15px 0;
  font-size: 15px;
  span {
    line-height: 40px;
  }
}
.el-tag {
  margin: 5px;
}
.input-new-tag {
  width: 120px;
}
</style>
